<?php
/**
 * 拍卖服务逻辑：
 * 1、计算离最近00、10、20、30、40、50结尾的分钟时间还有多少秒
 * 2、用这个秒来设置sleep时间
 * 3、取得有当前时间是否有拍卖场次，如果没有则sleep 60 秒再跳到第1步，如果有进入第4步
 * 4、把当前场次<paimai_special>的starttime=now(),state=1
 * 5、取得当前场次的要拍卖的车源列表，seq desc排序
 * 6、如果没有记录跳到8步，如果有记录进入第7步
 * 7、循环这个拍卖列表，从第一条开始，update paimai_special_car set starttime=now(), state=1然后 sleep(120)再执行拍卖结算函数
 * 8、循环结束执行场次结束函数
 * 9、跳入第一步
 *
 */

require_once(API_ROOT_PATH . '/../inc/Config.php');
require_once(API_ROOT_PATH . '/../inc/dblink.php');
require_once(API_ROOT_PATH . '/../inc/Mysql.php');


$dbh = false;//new dblink ( MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE );
$dbm = false;//new Mysql(MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE,'utf8',true);

function getNextSleepSecond()
{
    $date1 = time();
    $date2 = date('Y-m-d H:i:00', strtotime('+1 min', $date1));
    $date2 = strtotime($date2);
    $s = $date2 - $date1;

    $date1 = date('Y-m-d H:i:s', $date1);
    $date2 = date('Y-m-d H:i:00', $date2);

    echo("currtime:$date1   nexttime:$date2   timediff:$s\n");
    return $s;


    // $strm = date("i");
    // $date1 = date("Y-m-d H:i:s");
    //    $timediff = 10 - intval(substr($strm, strlen($strm)-1, strlen($strm)));
    // $date2 = date("Y-m-d H:i:00", strtotime("$date1 +$timediff min"));
    // $s = strtotime($date2)-strtotime($date1);
    // print_r("currtime:$date1   nexttime:$date2   timediff:$s\n");
    // return $s;
}


function parseSpecial($res)
{
    if ($res && is_array($res)) {
        $data = array("scene_id" => $res["scene_id"],
            "emp_id" => $res["emp_id"],
            "name" => $res["name"],
            "starttime" => $res["starttime"],
            "endtime" => $res["endtime"],
            "status" => $res["status"],
            "createtime" => $res["createtime"]

        );

        return $data;
    } else {
        return NULL;
    }
}

/*********处理场次************/
//状态（1 待拍,2 拍卖中,3 完毕）
function getOrderScene($strtime)
{
    global $dbm;
    $sql = "select * from `au_order_scene` where `status`=1 and `starttime`='$strtime' limit 1";
    $res = $dbm->fetchOne($sql);
    return parseSpecial($res);
}

function sceneStart($id)
{
    global $dbm;
    $sql = "update `au_order_scene` set `status`=2 where `scene_id`=$id";
    $dbm->query($sql);
}

function sceneEnd($id)
{
    global $dbm;
    $sql = "update `au_order_scene` set `status`=3, `endtime`=now() where `scene_id`=$id";
    $dbm->query($sql);
}

function getOrderList($scene_id)
{
    global $dbm;
    $sql = "select * from `au_order` where `scene_id`=$scene_id and `status`=3 order by `rank` asc";
    echo $sql . "\n";
    $data = $dbm->fetchAll($sql);
    return $data;
}


function microtime_time() {
    list($sec, $micro) = explode(" ", microtime());
    return ceil(((float) $sec + (float) $micro) * 1000);
}

/*********处理场次************/


/*********处理拍单************/
//拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8付付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功)]
function orderStart($id)
{
    global $dbm, $sid;
    //$sql = "SELECT * FROM (SELECT price,dealer_id FROM au_bid_log WHERE order_id='{$id}' GROUP BY dealer_id ORDER BY createtime DESC) AS price ORDER BY price DESC LIMIT 0,1";
    $sql = "SELECT price,dealer_id FROM au_bid_log a INNER JOIN (SELECT MAX(bid_id) bid_id FROM au_bid_log WHERE order_id='{$id}' GROUP BY dealer_id) b ON a.`bid_id` = b.bid_id ORDER BY price DESC LIMIT 1;";
    $res = $dbm->fetchOne($sql);
    $sql = "update `au_order` set bid_best_price='{$res['price']}',bid_best_dealer_id='{$res['dealer_id']}', `bidding_start_time`=now(), `status`=4 where `order_id`=$id";

    echo "|$sid|:" . '记入投标最高车商:' . $sql . "\n";
    $dbm->query($sql);

    if ($res['dealer_id']) {
        $sql = "call paimai_refund('{$id}' , '{$res['dealer_id']}' );";
        echo "|$sid|:" . '解冻投标阶段的保证金:' . $sql . "\n";
        $dbm->query($sql);
    } else {
        echo "|$sid|:" . '无人投标!' . "\n";
    }

    //更新拍单进度状态
//    $now = date('Y-m-d H:i:s', time());
    $now = microtime_time();
    $orderInfo = $dbm->fetchOne("select car_id from `au_order` where `order_id`=$id");
//    $sql = "UPDATE `au_order_trace_log` SET `action_log`=CONCAT(`action_log`,'" . $now . "/t开始竞拍/t--/n/t') WHERE `order_id` = '" . $id . "';";
    $sql = "INSERT INTO `au_order_trace_log_list` (`order_id`,`car_id`,`emp_name`,`action_no`,`action_name`,`createtime`) 
              VALUES($id, $orderInfo[car_id], '--',1007, '开始竞拍', $now)";
    $dbm->query($sql);
//    $sql = "UPDATE `au_car_trace_log` SET `action_log`=CONCAT(`action_log`,'" . $now . "/t开始竞拍/t--/n/t') WHERE `car_id` = (SELECT car_id FROM au_order WHERE order_id='" . $id . "' LIMIT 1);";
    $carInfo = $dbm->fetchOne("select owner_id from `au_cars` where `car_id` = $orderInfo[car_id]");
    $sql = "INSERT INTO `au_order_trace_log_list` (`car_id`,`owner_id`,`emp_name`,`action_no`,`action_name`,`createtime`) 
              VALUES($orderInfo[car_id], $carInfo[owner_id], '--', 1007, '开始竞拍', $now)";
    $dbm->query($sql);
}

function orderWaitBidding($ids)
{
    global $sid, $dbm;
    $new_ids = array();
    foreach ($ids as $key => $row) {
        array_push($new_ids, $row['order_id']);
    }
    $new_ids = implode(',', $new_ids);
    $sql = "update `au_order` set `status`=301 where `order_id` in ({$new_ids})";
    echo "|$sid|:" . '场内全部拍单列表:' . $new_ids . "\n";
    $dbm->query($sql);
}

function getOrderTimes($id)
{
    global $dbm;
    $sql = "select * from `au_order` where `order_id`=$id";
    $res = $dbm->fetchOne($sql);
    if ($res) return $res['act_elapsed_time'];
    else return 0;
}

function orderEnd($id)
{
    global $dbm, $sid;
    $sql = "call paimai_complete($id);";
    echo "|$sid|:" . '拍单结束:' . $sql . "\n";
    $dbm->query($sql);
    //更新拍单进度状态
    $now = microtime_time();
    $orderInfo = $dbm->fetchOne("select car_id from `au_order` where `order_id`=$id");
//    $sql = "UPDATE `au_order_trace_log` SET `action_log`=CONCAT(`action_log`,'" . $now . "/t竞拍结束/t--/n/t') WHERE `order_id` = '" . $id . "';";
    $sql = "INSERT INTO `au_order_trace_log_list` (`order_id`,`car_id`,`emp_name`,`action_no`,`action_name`,`createtime`) 
              VALUES($id, $orderInfo[car_id], '--', 1008, '竞拍结束', $now)";
    $dbm->query($sql);
//    $sql = "UPDATE `au_car_trace_log` SET `action_log`=CONCAT(`action_log`,'" . $now . "/t竞拍结束/t--/n/t') WHERE `car_id` = (SELECT car_id FROM au_order WHERE order_id='" . $id . "' LIMIT 1);";
    $carInfo = $dbm->fetchOne("select owner_id from `au_cars` where `car_id` = $orderInfo[car_id]");
    $sql = "INSERT INTO `au_order_trace_log_list` (`car_id`,`owner_id`,`emp_name`,`action_no`,`action_name`,`createtime`) 
              VALUES($orderInfo[car_id], $carInfo[owner_id], '--', 1008, '竞拍结束', $now)";
    $dbm->query($sql);
    //更新交易服务费
    $orderInfo = $dbm->fetchOne("select * from `au_order` where `order_id`=$id");
    $best_price = $orderInfo['bidding_best_price'] > $orderInfo['bid_best_price'] ? $orderInfo['bidding_best_price'] : $orderInfo['bid_best_price'];
    $commision = $best_price * PERCENTAGE;
    if ($commision <= MIN_FEE) {
        $commision = MIN_FEE;
    } elseif ($commision > MAX_FEE) {
        $commision = MAX_FEE;
    }
    $sql = "UPDATE `au_order` SET `commision`='" . $commision . "' WHERE `order_id`=$id";
    $dbm->query($sql);
}

function breachRedo($id)
{
    global $dbm;
    $sql = "select * from `au_order` where `order_id`=$id";
    $order = $dbm->fetchOne($sql);
    //拍单是否违约重拍
    $sql = "SELECT * FROM `au_cars` WHERE `car_id`=".$order['car_id'];
    $car = $dbm->fetchOne($sql);
    if($car['is_dealer_breach']==1){
        $old_order  = $dbm->fetchOne("select * from au_order where car_id={$order['car_id']} order by order_id desc limit 1,1");
        if(empty($old_order)){
            return;
        }
        $now = date("Y-m-d H:i:s");
        //判断车辆来源
        if($car['car_source']==1){ //4S店车源
            if($car['delivery_mode']==1){ //先付款后验车
                //更新拍单状态,待收款,添加财务收款信息,
                $sql = "UPDATE `au_order` SET `status`='8',`return_check_status`='5',`dealer_pay_status`='1'";
                if($car['pay_status']>=2){
                    $sql .= ",`first_pay_status`='1'";
                }
                $sql .= " WHERE order_id=$id";
                $dbm->query($sql);
                $sql = "INSERT INTO `au_proceeds_log` (`order_id`,'createtime') VALUES ($id,$now)";
                $dbm->query($sql);
            }else{ //先验车后付款
                $sql = "UPDATE `au_order` SET `status`='8',`return_check_status`='5',`check_car_status`='1'";
                if($car['pay_status']>=2){
                    $sql .= ",`first_pay_status`='1'";
                }
                $sql .= " WHERE order_id=$id";
                $dbm->query($sql);
                //添加车商验车信息,待验车
                //order_id,dealer_id,createtime,check_limit_time
                $dealer_id = $order['bidding_best_price'] > $order['bid_best_price'] ? $order['bidding_best_dealer_id'] : $order['bid_best_dealer_id'];
                $limit_time = date("Y-m-d H:i:s",strtotime("+1 day"));
                $sql = "INSERT INTO `au_car_dealer_check` (`order_id`,`dealer_id`,`createtime`,`check_limit_time`) VALUES ('$id','$dealer_id','$now','$limit_time')";
                $dbm->query($sql);
            }
        }else{ //个人车源
            $best_price = $order['bidding_best_price'] > $order['bid_best_price'] ? $order['bidding_best_price'] : $order['bid_best_price'] ;
            $first_money = $old_order['first_money'];
            if($best_price > $old_order['success_price']){
                $tail_money = $old_order['tail_money'];
            }else{
                $tail_money = $old_order['tail_money'] + ($best_price - $old_order['success_price']);
            }
            if($car['delivery_mode']==1){ //先付款后验车
                //添加收款信息,更新拍单信息
                //更新拍单状信息
                $sql = "UPDATE `au_order` SET `status`='8',`dealer_pay_status`='1',`first_money`='$first_money',`tail_money`='$tail_money'";
                if($car['pay_status']>=2){
                    $sql .= ",`first_pay_status`='1'";
                }
                $sql .= " WHERE order_id=$id";
                $dbm->query($sql);
                $sql = "INSERT INTO `au_proceeds_log` (`order_id`,'createtime') VALUES ($id,$now)";
                $dbm->query($sql);
            }else{ //先验车后付款
                //添加验车信息,更新拍单
                $sql = "UPDATE `au_order` SET `status`='8',`check_car_status`='1',`first_money`='$first_money',`tail_money`='$tail_money'";
                if($car['pay_status']>=2){
                    $sql .= ",`first_pay_status`='1'";
                }
                $sql .= " WHERE order_id=$id";
                $dbm->query($sql);
                //添加车商验车信息,待验车
                //order_id,dealer_id,createtime,check_limit_time
                $dealer_id = $order['bidding_best_price'] > $order['bid_best_price'] ? $order['bidding_best_dealer_id'] : $order['bid_best_dealer_id'];
                $limit_time = date("Y-m-d H:i:s",strtotime("+1 day"));
                $sql = "INSERT INTO `au_car_dealer_check` (`order_id`,`dealer_id`,`createtime`,`check_limit_time`) VALUES ('$id','$dealer_id','$now','$limit_time')";
                $dbm->query($sql);
            }
        }
    }
}

//获得场内定时拍单
function orderTimingOrder($sid)
{
    global $dbm;
    $sql = "select * from `au_order` where `scene_id`=$sid and bidding_start_time!='0000-00-00 00:00:00' and status=301";
    $data = $dbm->fetchAll($sql);
    return $data;
}

//获得场内当前时间定时拍单
function orderTimingOrderByTimer($sid, $timer = false)
{
    global $dbm;
    if (!$timer)
        $cur_time_id = date("Y-m-d H:i:00");
    else
        $cur_time_id = $timer;
    $sql = "select * from `au_order` where `scene_id`=$sid and bidding_start_time='$cur_time_id' and status=301";
    $data = $dbm->fetchAll($sql);
    return $data;
}

//获得场内所有非定时拍单
function orderNotTimingOrder($sid)
{
    global $dbm;
    $sql = "select * from `au_order` where `scene_id`=$sid and bidding_start_time='0000-00-00 00:00:00' and status=301";
    $data = $dbm->fetchAll($sql);
    return $data;
}

//获得指定时间点的所有场
function getScenes($timer)
{
    global $dbm;
    $sql = "select * from `au_order_scene` where `status`=1 and `starttime`='$timer'";
    $data = $dbm->fetchAll($sql);
    return $data;
}

//等待进程id列表结束$pids=[pid1,pid2,pid...];
function wait_pids($pids)
{
    while (count($pids) > 0) {
        //echo 'aaa',"\n";
        foreach ($pids as $key => $pid) {
            $res = pcntl_waitpid($pid, $status, WNOHANG);

            if ($res == -1 || $res > 0)
                unset($pids[$key]);
        }
        sleep(1);
    }
}

//获得数据库操作对象
function get_mysql_handler()
{
    $dbm = new Mysql(MYSQLDB, MYSQLDB_USER, MYSQLDB_PWD, MYSQLDB_DATABASE, 'utf8', false);
    return $dbm;
}